<?php

namespace app\admin\model\facrm;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Record extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'facrm_record';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';


    /**
     * 创建者
     */
    public function createUser()
    {
        return $this->hasOne('\app\admin\model\Admin', 'id', 'create_user_id');
    }

    /**
     * 客户对象
     * @return \think\model\relation\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo('\app\admin\model\facrm\Customer', 'types_id', 'id');
    }

    /**
     * 线索对象
     * @return \think\model\relation\BelongsTo
     */
    public function clues()
    {
        return $this->belongsTo('\app\admin\model\facrm\Clues', 'types_id', 'id');
    }

    /**
     * 商机需求对象
     * @return \think\model\relation\BelongsTo
     */
    public function business()
    {
        return $this->belongsTo('\app\admin\model\facrm\Business', 'types_id', 'id');
    }
    /**
     * 附件
     * @return \think\model\relation\HasMany
     */
    public function files(){
        return $this->hasMany('\app\admin\model\facrm\record\Files','record_id','id');
    }

    /**
     * 跟进趋势Echart
     * @return bool
     */
    public function getRecordEchartData($startDate,$endDate,$owner_user_ids,$types="customer")
    {

        $recordModel = $this;
        // 生成查询的开始和结束时间，默认取30日
        !is_numeric($startDate) && $starttime = strtotime($startDate);
        !is_numeric($endDate) && $endtime = strtotime($endDate);
        $isnotrangeDate = empty($starttime) && empty($endtime);

        $nearly = '30';
        if ($isnotrangeDate) {
            $endtime = time();
            $nearly -= 1;
            $starttime = strtotime("-{$nearly} day");  // 最近30天日期
        } elseif ($starttime > $endtime) {
            $this->error = '起始时间要小于终止时间';
            return false;
        }
        $totalseconds = $endtime - $starttime;;
        if ($totalseconds > 86400 * 30 * 2) {
            $format = '%Y-%m';
        } else {
            if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
        }
        if ($owner_user_ids&&is_numeric($owner_user_ids)){
            $recordModel->where('create_user_id', $owner_user_ids);
        }elseif($owner_user_ids&&is_array($owner_user_ids)){
            $recordModel->where('create_user_id','in', $owner_user_ids);
        }
        //跟进次数
        $lists = $recordModel->where('types', $types)->where('create_time', 'between time', [$starttime, $endtime])
            ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(create_time), "' . $format . '") AS add_date')
            ->group('add_date')
            ->select();

        //客户数量
        if ($owner_user_ids&&is_numeric($owner_user_ids)){
            $recordModel->where('create_user_id', $owner_user_ids);
        }elseif($owner_user_ids&&is_array($owner_user_ids)){
            $recordModel->where('create_user_id','in', $owner_user_ids);
        }
        $tempsql = $recordModel->field('max(id) id,types,max(create_time) create_time,types_id')->where('types', $types)->where('create_time', 'between time', [$starttime, $endtime])->group('types_id')->buildSql();
        $listsd = Db::query("SELECT COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(create_time), \"%Y-%m-%d\") AS add_date FROM ($tempsql) as r GROUP BY `add_date`");


        if ($totalseconds > 84600 * 30 * 2) {
            $starttime = strtotime('last month', $starttime);
            while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                $column[] = date('Y-m', $starttime);
            }
        } else {
            if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
        }


        $c_count = $d_count = array_fill_keys($column, 0);

        foreach ($lists as $k => $v) {
            $c_count[$v['add_date']] = $v['nums'];//
        }

        foreach ($listsd as $k => $v) {
            $d_count[$v['add_date']] = $v['nums'];
        }

        $result = [
            'date' => array_keys($c_count),
            'd_count' => array_values($d_count),
            'c_count' => array_values($c_count),
        ];

        $data = [
            'date' => $result['date'],
            'data' => [
                "跟进客户" => $result['d_count'],
                "跟进次数" => $result['c_count'],
            ],
        ];
        return $data;

    }

    /**
     * 获取跟进类型文本
     * @param $value
     * @param $data
     * @return string
     */
    public function getRecordTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['record_type']) ? $data['record_type'] : '');
        $list = $this->getRecordTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    /**
     * 获取跟进类型
     * @ApiInternal
     */
    public function getRecordTypeList()
    {
        $config = get_addon_config('facrm');
        return $config['record_type'];
    }

}